/**
 * 
 */
package com.vmix.android.vmixsdk.rds;

import java.util.ArrayList;

import com.vmix.android.vmixsdk.exception.VmixException;
import com.vmix.android.vmixsdk.valueobject.VmixCollections;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

/**
 * @author lei
 *
 */
public class GetCollectionsService extends Service {
	
	// define a broadcast type
	public static final String COLLECTIONS_FOUND = "collections_found";
	
	protected GetCollectionsOperation operation = null;
	private VmixCollections _collections = null;

	public Thread thread;
	private final IBinder binder = new GetCollectionsBinder();

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	
	/* (non-Javadoc)
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		
		return binder;
		
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// Retrieve the shared preferences
		// Context context = getApplicationContext();

		this.thread = new Thread( null, this.doBackgroundThreadProcessing, "getCollectionOperationThread");
		
		// start the thread
		this.thread.start();
		
		// pushing the thread onto the threads array
		// this.threads.add( thread );
		
		return Service.START_STICKY;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		// stopping running threads
		this.stopThreads();
	}

	/**
	 * 
	 * @return
	 */
	public VmixCollections getCollections()
	{
		return this._collections;
	}
	

	/**
	 * custom binder for getCollectionsService
	 * 
	 * @author lei
	 *
	 */
	public class GetCollectionsBinder extends Binder {
		public GetCollectionsService getService() {
			return GetCollectionsService.this;
		}
	}
	
	// define background runnable
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		public void run() {
			performGetCollections();
		}
	};
	
	/**
	 * execute get collections
	 */
	private void performGetCollections() {
		
		try {
			
			this.operation = new GetCollectionsOperation();
			
			this._collections = this.operation.process();

			// if we have collections, broadcast it
			if( ! this._collections.isEmpty() ) {
				
				this.onLoadComplete();
				
			}
		}
		catch( VmixException e ) {
		
			//TODO
		}
	}
	
	/**
	 * announce load complete for anyone who listens
	 */
	private void onLoadComplete() {
		// stopping all the running threads
		// this.stopThreads();
		
		// create new intent
		Intent intent = new Intent( GetCollectionsService.COLLECTIONS_FOUND );
		
		// broadcast
		sendBroadcast( intent );
		
	}
	
	// stopping all the running threads
	private void stopThreads() {

		// stopping
		if( this.thread.isAlive() ) {
		
			this.thread.stop();
		}
	}
}
